<template>
  <div class="fa" :style="{ height: faheight }">
    <div class="title-sign">样本入库</div>
    <a-form ref="userform" :model="formdata" name="basic" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }"
      autocomplete="off">
      <a-row style="height: 45px">
        <a-col :span="6">
          <a-form-item label="入库单号" name="id">
            <a-input v-model:value="formdata.id" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="出库日期">
            <a-date-picker :disabled="anttabs?.order >= 1" v-model:value="formdata.cautionTime" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="title-sign">选择样本</div>
    <a-form ref="userform" :model="searchdata" name="basic" :wrapper-col="{ span: 20 }" autocomplete="off">
      <a-row style="height: 40px">
        <a-col :span="1" style="text-align: center; height: 32px; line-height: 32px"> 查询条件 </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-select allowClear v-model:value="searchdata.projectId" placeholder="课题组">
              <a-select-option v-for="j in antSelect" :value="j.id" :key="j.id">{{ j.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-input v-model:value="searchdata.originalSerial" placeholder="编号" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-input v-model:value="searchdata.name" placeholder="样本名称" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item>
            <a-input v-model:value="searchdata.extDataList[0].value" placeholder="样本类型" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" style="margin-left: 10px; height: 30px" @click="sampledata()">查询</a-button>
        </a-col>
      </a-row>
    </a-form>
    <vxe-table border ref="xTable1" :data="tableData" :checkbox-config="tableCheckboxConfig"
      @checkbox-all="selectAllChangeEvent1" max-height="220px" align="center" :row-config="{ height: 35 }" show-overflow
      @checkbox-change="selectChangeEvent1">
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column v-for="item in tabColumn" :key="item.field" :field="item.field" :title="item.title"></vxe-column>
    </vxe-table>
    <tabs @deltabData="deltabData" @authority="authority" :manageLinkList="manageLinkList" @fomeDataId="fomeDataId"
      @depositing="depositing" :formTime="formdata.cautionTime" :formNo="formdata.id" ref="anttabs"
      @removeAdd="removeAdd"></tabs>
    <div style="display: flex; justify-content: center; width: 90%; margin-top: 10px">
      <a-button type="primary" style="margin-right: 10px" @click="renovate" :disabled="anttabs?.order != 0">重置</a-button>
      <a-button type="primary" @click="storageTree" :disabled="anttabs?.order != 2">确认入库</a-button>
    </div>
  </div>
  <Modal :destroyOnClose="true" :maskClosable="false" :footer="null" title="底单存档" width="60%"
    v-model:visible="showHighCamera">
    <HighCameracopy @uploadSuccess="uploadSuccess" :routerRecord="true" highCameraId="inputManageHighCamera"
      canvasCameraId="inputManageCanvasCamera" :billId="inputFromid" :billType="1" :processCfg="processCfg">
    </HighCameracopy>
  </Modal>
  <!-- //入库等待提示框 -->
  <a-drawer title="入库状态" width="80%" :visible="visibleloading" @close="onClose">
    <p>入库单号 : {{ formdata.id }}</p>
    <div style="width: 80%; height: 90%">
      <vxe-table border="default" ref="vxeTable123" :data="promptData" max-height="80%" :row-config="{ height: 35 }"
        show-overflow>
        <vxe-column field="boxNo" title="冻存盒编号"></vxe-column>
        <vxe-column field="specimenCount" title="入库数量"></vxe-column>
        <vxe-column field="storageName" title="入库设备" width="170px"></vxe-column>
        <vxe-column field="sampleAddress" title="操作">
          <template #default="{ row }">
            <span v-if="row.deviceId == 0">放入完毕</span>
            <span v-else>
              <span v-if="row.status == 0" style="color: skyblue">设备正在执行自动存放，请等待…</span>
              <span v-else-if="row.status == 1">放入完毕</span>
              <span v-else style="color: red">放入失败</span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div style="display: flex; justify-content: center; align-items: center">
      <a-button type="primary" style="margin-right: 10px" @click="onClose">关闭</a-button>
      <a-button type="primary" @click="openHigh" :disabled="nextStep">下一步</a-button>
    </div>
  </a-drawer>
  <Modal :destroyOnClose="true" title="失败" :maskClosable="false" width="30%" :footer="null" v-model:visible="failvisible">
    <p style="text-align: center; font-size: 16px; margin-bottom: 10px">样本入库失败,请选择下一步操作:</p>
    <div style="width: 100%; display: flex; justify-content: center; align-items: center; margin-bottom: 10px">
      <a-button type="primary" style="margin-right: 20px" @click="retry(true)">重试</a-button>
      <a-button type="primary" @click="retry(false)">忽略</a-button>
    </div>
  </Modal>
</template>
<script setup lang="tsx">
import { modal, VxeTableEvents } from 'vxe-table';
import { reactive, ref, computed, watch, onBeforeUnmount } from 'vue';
import { singleSearch, getBillno, inputUpdate, getBasicPointList, billInPutin, billInIgnore, inputGetById } from '../../api/input_manage';
import { taskSearch } from '@/api/base/task-data';
import { message, Modal } from 'ant-design-vue';
import { userSearch } from '@/api/operationFlow';
import tabs from './components/tabs.vue';
import HighCameracopy from '@/components/photograph/HighCameracopy.vue';
import { useRoute, useRouter } from 'vue-router';
import MQTT from '@/framework/utils/mqtt';
import { addSpecimenType, padData } from '@/libs/utils';
import dayjs from 'dayjs';
const route = useRoute();
const anttabs = ref();
const router = useRouter();
const showHighCamera = ref(false);
const nextStep = ref(true);
const failvisible = ref(false);
const vxeTable123 = ref();
const tabColumn = ref([
  { field: 'originalSerial', title: '样本编号' },
  { field: 'name', title: '样本名称' },
  { field: 'specimen_type', title: '样本类型' },
  { field: 'serial', title: '数字编号' },
  { field: 'newcapacity', title: '容量' },
  { field: 'projectName', title: '项目组' },
  { field: 'sampleTime', title: '采样日期' },
  { field: 'sampleAddress', title: '采样地点' },
  { field: 'preservUserName', title: '负责人' },
]);
const formdata: any = reactive({
  id: '',
  cautionTime: null,
});
const antSelect = ref([]);
const searchdata = reactive({
  projectId: null,
  originalSerial: '',
  name: '',
  extDataList: [
    {
      name: 'specimen_type',
      value: '',
    },
  ],
  categoryName: '',
});
const manageLinkList = ref([]);
//权限管理
const processCfg = reactive({
  isArchive: true, //是否开启底单存档文件上传
  isCapture: true, //是否开启高拍仪
  isSignature: true, //是否开启电子签名
});
// 获取审批流程配置
const authority = async (data) => {
  let specimenOutableVoList = [];
  data.forEach((el) => {
    let arr = el.list ? el.list : el.subSpecimens;
    specimenOutableVoList.push(...arr);
  });
  const res = await userSearch({ type: 2, specimenOutableVoList });
  processCfg.isArchive = res.result.processCfg.isArchive;
  processCfg.isCapture = res.result.processCfg.isCapture;
  processCfg.isSignature = res.result.processCfg.isSignature;
};

const taskxiangmuz = (async () => {
  let queryOpt = {
    pageNum: 1, // 当前页数
    pageSize: 1000, // 页面大小
    'orderBy[0].field': 'createTime', // 默认排序字段
    'orderBy[0].order': 'desc', // 默认排序方式
  };
  let { result } = await taskSearch(queryOpt);
  antSelect.value = result.data;
})();
const fomeDataId = (data) => {
  formdata.id = data[0];
  if (data[1]) {
    formdata.cautionTime = dayjs(data[1], 'YYYY-MM-DD')
  }
};
const uploadSuccess = () => {
  showHighCamera.value = false;
};
const storageTree = async () => {
  if (anttabs.value?.panes.some((item) => item.serialId == '')) return message.warning('还有盒子未选择存储位置');
  let arr = anttabs.value.panes.map((item) => ({
    epcId: item.id,
    storageDesp: item.storageDesp,
    storageId: item.serialId,
    submitStatus: 3,
    deviceId: item.deviceId,
  }));
  let data = { id: anttabs.value.check.id, stocks: arr, status: 2 };
  let { result } = await inputUpdate(data);
  padData(anttabs.value?.panes, formdata.id, 'IN');
  if (result == 3) {
    Modal.confirm({
      title: '请将样本存入指定位置',
      onOk: async () => {
        message.success('存放样本成功');
        MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
        anttabs.value.order = 3;
      },
      onCancel() {
        message.success('存放样本成功');
        MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
        anttabs.value.order = 3;
      },
    });
  } else {
    visibleloading.value = true;
    websort();
  }
};

const timer: any = ref(null);
const promptData = ref([]);
//每5s刷新数据
const websort = async () => {
  seejidian();
  timer.value = setInterval(async () => {
    seejidian();
  }, 5000);
};
// 查看是否有基点任务
const seejidian = async () => {
  try {
    const { result } = await getBasicPointList({
      billId: anttabs.value.check.id,
      billType: 1,
    });
    promptData.value = result.dataList;
    vxeTable123.value?.loadData(promptData.value);
    if (result.dataList.some((item) => item.status == 2)) {
      failvisible.value = true;
      clearInterval(timer.value);
    }
    if (result.dataList.every((item) => item.status == 1)) {
      nextStep.value = false;
      let arr = anttabs.value.panes.map((item) => ({
        epcId: item.id,
        storageDesp: item.storageDesp,
        storageId: item.serialId,
        submitStatus: 3,
        deviceId: item.deviceId,
      }));
      let data = { id: anttabs.value.check.id, stocks: arr, status: 3 };
      await inputUpdate(data);
      clearInterval(timer.value);
    }
  } catch (error) {
    router.push({ name: 'input_record' });
  }

};
// 基点任务失败重试和忽略
const retry = async (bol) => {
  if (bol) {
    // 基点任务失败重试
    let { result } = await inputGetById(anttabs.value.check.id)
    let arr = promptData.value.filter(item => item.status == 2).map(el => el.boxNo)
    let newArr = []
    arr.forEach(item => {
      result.stocks.forEach(el => {
        if (el.boxInstanceSerial == item) newArr.push(el)
      })
    })
    billInPutin(anttabs.value.check.id, { stocks: newArr, batchNo: formdata.id }).then((res) => {
      failvisible.value = false;
      websort();
    });
  } else {
    // 基点任务失败忽略
    let { result } = await inputGetById(anttabs.value.check.id)
    let arr = promptData.value.filter(item => item.status == 2).map(el => el.boxNo)
    let newArr = []
    result.stocks.forEach(item => {
      if (arr.includes(item.boxInstanceSerial)) newArr.push(item)
    })
    await billInIgnore(anttabs.value.check.id, { stocks: newArr, batchNo: formdata.id });
    for (let i = 0; i < result.stocks.length; i++) {
      if (arr.includes(result.stocks[i].boxInstanceSerial)) {
        result.stocks.splice(i, 1)
        anttabs.value.panes.splice(i, 1);
        i--
      }
    }
    failvisible.value = false;
    websort();
  }
};

const faheight = ref(window.innerHeight + 'px');
if (!route.query.id) {
  const Billno = (async () => {
    let { result } = await getBillno();
    formdata.id = result;
  })();
}
const tableData: any = ref([]);
let checkok = computed(() => {
  return anttabs.value?.panes.length > 0 && anttabs.value?.order == 0;
});
const tableCheckboxConfig: any = reactive({
  checkMethod: () => {
    return checkok.value;
  },
});
const request = ref(true);
const settime = ref(0);
const sampledata = async () => {
  if (Date.now() - settime.value < 2000) return;
  settime.value = Date.now();
  let queryOpt = {
    pageNum: 1, // 当前页数
    pageSize: 200, // 页面大小
    // paging: false,
    sort: 'createTime', // 默认排序字段
    order: 'desc', // 默认排序方式
    notBindBox: '1',
    queryExtData: true,
  };
  let arr = [];
  anttabs?.value?.panes.forEach((item) => {
    arr.push(...item.list);
  });
  queryOpt.pageSize += arr.length;
  const { result } = await singleSearch(searchdata, queryOpt);
  addSpecimenType(result.data);
  arr.forEach((item) => {
    let index = result.data.findIndex((el) => el.id == item.id);
    if (index != -1) {
      result.data.splice(index, 1);
    }
  });
  tableData.value = result.data;
  request.value = tableData.value.length >= 200;
  xTable1.value.loadData(tableData.value);
};
// 重置
const sampledata2 = async () => {
  let queryOpt = {
    pageNum: 1, // 当前页数
    pageSize: 200, // 页面大小
    // paging: false,
    sort: 'createTime', // 默认排序字段
    order: 'desc', // 默认排序方式
    notBindBox: '1',
    queryExtData: true,
  };
  const { result } = await singleSearch(searchdata, queryOpt);
  addSpecimenType(result.data);
  tableData.value = result.data;
  xTable1.value.loadData(tableData.value);
};
//查询

sampledata();
watch(
  () => tableData.value.length,
  (val, prevVal) => {
    if (val < 100 && request.value) {
      sampledata();
    }
  },
);
watch(
  () => anttabs.value?.order,
  (val, prevVal) => {
    if (val == 3) showHighCamera.value = true;
  },
);
const inputFromid = ref(123);
watch(
  () => anttabs.value?.check.id,
  (val, prevVal) => {
    val ? (inputFromid.value = val) : '';
  },
);
const xTable1 = ref();
const selectChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked }) => {
  const table: any = xTable1.value;
  const records: any = table.getCheckboxRecords();
  table.removeCheckboxRow();
  anttabs.value.linkage(records);
  tableData.value.splice(
    tableData.value.findIndex((item) => item.id == records.id),
    1,
  );
};
const selectAllChangeEvent1: VxeTableEvents.CheckboxChange = ({ checked }) => {
  const table = xTable1.value;
  const records = table.getCheckboxRecords();
  table.removeCheckboxRow();
  anttabs.value.linkage(records);
  tableData.value = [];
  // console.log(checked ? '勾选事件' : '取消事件', records)
};
// 重置
const renovate = () => {
  Modal.confirm({
    title: '确定重置入库单吗?',
    onOk() {
      sampledata2();
      anttabs.value.resetInput();
    },
    onCancel() { },
  });
};
//下面表单移除事件
const removeAdd = (row) => {
  xTable1.value.insertAt(row, 0);
};
//等待框显示
const visibleloading = ref(false);
//等待框关闭事件
const onClose = () => {
  visibleloading.value = false;
  clearInterval(timer.value);
  timer.value = null;
};
//下一步
const openHigh = () => {
  onClose();
  showHighCamera.value = true;
};
const depositing = () => {
  visibleloading.value = true;
  websort();
};
onBeforeUnmount(() => {
  MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
  onClose();
});
//删除盒子后把数据塞回去上面
const deltabData = () => {
  sampledata();
};
</script>
<style lang="less" scoped>
.fa {
  width: 100%;
  height: 100%;
  background-color: #fff;
  position: relative;
  padding: 10px;
  overflow: auto;
}
</style>
